package com.netty.encodedecode;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.Delimiters;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.util.CharsetUtil;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * @auther: cc.ly
 * @date: 2019/1/12/012
 */

public class Client {
    public static void main(String[] args) throws InterruptedException, IOException {
        EventLoopGroup work = new NioEventLoopGroup();

        Bootstrap b = new Bootstrap();

        b.group(work).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                ChannelPipeline pipeline = ch.pipeline();
                ch.pipeline().addLast(new DelimiterBasedFrameDecoder(4096, Delimiters.lineDelimiter()));
                ch.pipeline().addLast(new StringDecoder(CharsetUtil.UTF_8));
                ch.pipeline().addLast(new StringEncoder(CharsetUtil.UTF_8));
                pipeline.addLast(new ClientHandler());
            }
        });
        ChannelFuture channelFuture = b.connect("localhost", 8888).sync();
        Channel channel = channelFuture.channel();
        //BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        for (; ; ) {
            Long ll = 11L;
            channel.writeAndFlush(ll + "");
            Thread.sleep(300);
        }
    }
}
